package site.qjdb.controller;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import site.qjdb.constant.Info;
import site.qjdb.pojo.*;
import site.qjdb.pojo.response.CommonResult;
import site.qjdb.pojo.response.ResponseCode;
import site.qjdb.service.*;
import site.qjdb.util.CommonUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/reply")
public class ReplyController {
	@Resource
	private UserService userService;
	@Resource
	private CommentService commentService;
	@Resource
	private GoodsService goodsService;
	@Resource 
	private ReplyService replyService;
	@Resource
	private NoticeService noticeService;
	@Resource
	private WantService wantService;
	
	/**
	 * 	添加回复（留言）
	 * 	commentId：留言id，必传
	 * 	gid：留言所在的商品id，必传
	 * 	content：留言内容，必传
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/addByComment", method = RequestMethod.POST)
	public Object addByComment(@RequestParam("id1") String commentId,
			@RequestParam("id2") String gid,
			@RequestParam String content,
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		if("".equals(content.trim())) {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT);
		}
		try {
			Integer gidInteger = Integer.parseInt(gid);
			// 根据gid查找Goods，查看状态是否为1（通过）
			Goods _goods = new Goods();
			_goods.setGid(gidInteger);
			_goods.setState(1);
			Goods newGoods = goodsService.findGoods(_goods);
			if(newGoods == null) {
				throw new Exception();
			}
			Integer commentIdInteger = Integer.parseInt(commentId);
			// 根据commentId，gid查找Comment，查看是否存在
			Comment _comment = new Comment();
			_comment.setCommentId(commentIdInteger);
			_comment.setGoods(_goods);
			_comment.setIsDel(0);
			Comment newComment = commentService.findComment(_comment);
			if(newComment == null) {
				throw new Exception();
			}
			// 解决特殊字符是空白的问题
			content = URLDecoder.decode(URLEncoder.encode(content, "UTF-8"),"UTF-8");
			// 添加回复
			Reply reply = new Reply();
			// 回复内容
			reply.setContent(content);
			// 所从属于的留言id
			reply.setSuperiorId(commentIdInteger);
			// 回复时间
			reply.setTime(new Date());
			// 设置为留言回复
			reply.setType(0);
			// 未删除
			reply.setIsDel(0);
			User _user = new User();
			_user.setUid((((User)session.getAttribute(Info.USER_SESSION)).getUid()));
			reply.setUser(_user);
			// 添加回复信息
			replyService.addReply(reply);
			// 设置通知
			Notice notice = new Notice();
			// 对应回复id
			notice.setRid(reply.getRid());
			// 未删除
			notice.setIsDel(0);
			// 新通知
			notice.setIsNew(1);
			// 类型：回复我的留言（11）
			notice.setType(11);
			// 时间
			notice.setTime(new Date());
			// 接收用户
			notice.setUid(newComment.getUser().getUid());
			// 添加通知
			noticeService.addNotice(notice);
			return new CommonResult<>(ResponseCode.SUCCESS, reply);
		}catch(Exception e) {
			return new CommonResult<>(ResponseCode.COMMENT_NOT_FOUND);
		}
	}
	
	/**
	 *	删除回复 （留言）
	 * 	参数1：回复id
	 * 	参数2：留言id
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/deleteByComment", method = RequestMethod.POST)
	public Object deleteByComment(@RequestParam("id1") String rid,
			@RequestParam("id2") String commentId,
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		try {
			Integer ridInteger = Integer.parseInt(rid);
			Integer commentIdInteger = Integer.parseInt(commentId);
			replyService.deleteReplyByComment(ridInteger,
					((User)session.getAttribute(Info.USER_SESSION)).getUid(), 
					commentIdInteger);
			// 删除对应通知
			Notice notice = new Notice();
			notice.setRid(ridInteger);
			notice.setType(11);
			noticeService.deleteNotice(notice);
			return new CommonResult<>(ResponseCode.SUCCESS);
		}catch(Exception e) {
			return new CommonResult<>(ResponseCode.COMMENT_NOT_FOUND);
		}
	}
	
	/**
	 * 	添加回复（求购信息）
	 * 	wid：求购信息id，必传
	 * 	content：留言内容，必传
	 * 	@throws UnsupportedEncodingException 
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/addByWant", method = RequestMethod.POST)
	public Object addByWant(@RequestParam("id") String wid,
			@RequestParam String content,
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) throws UnsupportedEncodingException {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		if("".equals(content.trim())) {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT);
		}
		try {
			Integer widInteger = Integer.parseInt(wid);
			// 根据commentId，gid查找Comment，查看是否存在
			Want _want = new Want();
			_want.setWid(widInteger);
			_want.setIsDel(0);
			Want newWant = wantService.findWant(_want);
			if(newWant == null) {
				throw new Exception();
			}
			// 解决特殊字符是空白的问题
			content = URLDecoder.decode(URLEncoder.encode(content, "UTF-8"),"UTF-8");
			// 添加回复
			Reply reply = new Reply();
			// 回复内容
			reply.setContent(content);
			// 所从属于的留言id
			reply.setSuperiorId(widInteger);
			// 回复时间
			reply.setTime(new Date());
			// 设置为求购信息回复
			reply.setType(1);
			// 未删除
			reply.setIsDel(0);
			User _user = new User();
			_user.setUid((((User)session.getAttribute(Info.USER_SESSION)).getUid()));
			reply.setUser(_user);
			// 添加回复信息
			replyService.addReply(reply);
			// 设置通知
			Notice notice = new Notice();
			// 对应回复id
			notice.setRid(reply.getRid());
			// 未删除
			notice.setIsDel(0);
			// 新通知
			notice.setIsNew(1);
			// 类型：回复我的求购信息 （12）
			notice.setType(12);
			// 时间
			notice.setTime(new Date());
			// 接收用户
			notice.setUid(newWant.getUser().getUid());
			// 添加通知
			noticeService.addNotice(notice);
			return new CommonResult<>(ResponseCode.SUCCESS, reply);
		}catch(Exception e) {
			return new CommonResult<>(ResponseCode.COMMENT_NOT_FOUND);
		}
	}
	
	/**
	 *	删除回复 （求购信息）
	 * 	参数1：回复id
	 * 	参数2：求购信息id
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/deleteByWant", method = RequestMethod.POST)
	public Object deleteByWant(@RequestParam("id1") String rid,
			@RequestParam("id2") String wid,
			HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) {
		// 处理session和Cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		try {
			Integer ridInteger = Integer.parseInt(rid);
			Integer widInteger = Integer.parseInt(wid);
			replyService.deleteReplyByWant(ridInteger,
					((User)session.getAttribute(Info.USER_SESSION)).getUid(), 
					widInteger);
			// 删除对应通知
			Notice notice = new Notice();
			notice.setRid(ridInteger);
			notice.setType(12);
			noticeService.deleteNotice(notice);
			return new CommonResult<>(ResponseCode.SUCCESS);
		}catch(Exception e) {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT);
		}
	}
	
	/**
	 * 	查询回复（求购信息）
	 * 	id：求购信息id
	 * 
	 * */
	@ResponseBody
	@RequestMapping("/findReplys")
	public Object findReplys(@RequestParam("id") String wid) {
		try {
			List<Reply> replyList = replyService.findReplyAll(Integer.parseInt(wid));
			return new CommonResult<>(ResponseCode.SUCCESS, replyList); 
		}catch(Exception e) {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT); 
		}
	}
}
